<?php namespace modules\material;
/**
 * @subpackage  \modules\material
 *
 * @copyright   Copyright (C) 2013 - 2014 Mailerm, Inc. All rights reserved.
 */

# Load Libraries
require_once MPATH_LIBRARIES . '/database/MySQL.php';
use \MySQL as MySQL;

# Load Configuration
require_once MPATH_MODULES . '/configuration.php';

# Load Modules
require_once MPATH_MODULES . '/mod_user/mod_user.php';
use \modules\user as mod_user;

# Load Models
require_once MPATH_MODULES . '/shared/model_material.php';
require_once MPATH_MODULES . '/shared/model_project.php';

use \shared\model\material as Material;
use \shared\model\project as Project;

// Add Project Material
//-1 项目已结束
// 0 添加成功
// 1 项目进行中
// 2 项目不可用
// 4 服务端异常
function add($params, $method, $app) {
	// Check Role
    if (!mod_user\_user_belong(array(ROLE_PLANNER))) {
        $app->return_error(403, 'Forbidden', 'You don\'t have permission to access this server.');
        exit();
    }
    

    echo "called";

    $result['status'] = 4;
    $app->return_json($result);
    exit();
}

// find materials
//-1:用户未登录
// 0:
// 1:输入信息有误
// 2:项目不可用
// 3:
// 4:服务器异常
// 5:角色存在不可添加
function find($params, $method, $app) {
    // Check Role
    if (!mod_user\_user_belong(array(ROLE_MANAGER, ROLE_PLANNER))) {
        exit();
    }
    $start = isset($params['iDisplayStart']) ? intval($params['iDisplayStart']) : 0;
    $size = isset($params['iDisplayLength']) ? intval($params['iDisplayLength']) : 10;
    $result = array();
    $result['sEcho'] = isset($params['sEcho']) ? intval($params['sEcho']) : 1;
    
    // Check project
    $project = isset($params['project']) ? $params['project'] : -1;
    if ($project == -1) {
        $result['status'] = 1;
        $app->return_json($result);
        exit();
    }
    $project = Project\get($project);
    if ($project == null) {
        $result['status'] = 2;
        $app->return_json($result);
        exit();
    }

    # Num Rows
    $total = Material\count($project['id']);
    if ($total < 1) {
        $result['iTotalRecords'] = 0;
        $result['iTotalDisplayRecords'] = 0;
        $result['aaData'] = array();
        $app->return_json($result);
        exit(); 
    }
    # Find Page
    $projects = Material\find($project['id'], $start, $size);
    # Num Rows
    if(count($projects) < 1) {
        $result['iTotalRecords'] = 0;
        $result['iTotalDisplayRecords'] = 0;
        $result['aaData'] = array();
        $app->return_json($result);
        exit(); 
    }
    
    $result['iTotalRecords'] = $total;
    $result['iTotalDisplayRecords'] = $total;
    $result['aaData'] = array();
    foreach ($projects as $key => $project) {
        $row = array();
        foreach ($project as $key => $value) $row[] = $value;
        $result['aaData'][] = $row;
    }

    $app->return_json($result);
    exit();
}